package com.sk.weichat.ui.message.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SearchRoomAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.SearchUserAndRoomBean;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.ui.groupchat.ApplyForAddGroupActivity;
import com.sk.weichat.ui.groupchat.OpenGroupInfoActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * @Author: chenzl
 * @ClassName: NetSearchRoomsActivity
 * @Description: 网络搜索群聊
 * @CreateDate: 2019/9/16 15:00
 */
public class NetSearchRoomsActivity extends EditBaseActivity implements View.OnClickListener {

    private ImageView iv_title_left;
    private EditText et_search_user;
    private ImageView ivClear;
    private TextView tv_finish_search_user;
    private LinearLayout ll_layout_search_empty;
    private LinearLayout linearTip;
    private TextView tvSearchText;

    private LinearLayout ll_query_group;
    private RecyclerView recyGroup;
    private SearchRoomAdapter mSearchRoomAdapter;
    private List<SearchUserAndRoomBean.RoomsBean> roomList = new ArrayList<>();
    private String search_user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_search_rooms);
        getSupportActionBar().hide();
        search_user = getIntent().getStringExtra("search_user");//搜索内容
        initView();
        onLoadData(search_user);
    }

    private void initView() {
        iv_title_left = findViewById(R.id.iv_title_left);
        et_search_user = findViewById(R.id.et_search_user);
        ivClear = findViewById(R.id.iv_clear_user);
        tv_finish_search_user = findViewById(R.id.tv_finish_search_user);
        ll_layout_search_empty = findViewById(R.id.ll_layout_search_empty);
        linearTip = findViewById(R.id.linear_search_tip);
        tvSearchText = findViewById(R.id.tv_search_text);
        ll_query_group = findViewById(R.id.ll_query_group);
        recyGroup = findViewById(R.id.recy_group);
        recyGroup.setLayoutManager(new LinearLayoutManager(this));

        mSearchRoomAdapter = new SearchRoomAdapter(coreManager, roomList);
        recyGroup.setAdapter(mSearchRoomAdapter);
        mSearchRoomAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.layout_search_group_item:
                        startActivity(new Intent(NetSearchRoomsActivity.this, OpenGroupInfoActivity.class)
                                .putExtra("RoomId", roomList.get(position).getId())
                                .putExtra("RoomJid", roomList.get(position).getJid()));
                        break;
                    case R.id.tv_search_add:
                        roomAutoJoin(roomList.get(position));
//                        startActivity(new Intent(NetSearchRoomsActivity.this, ApplyForAddGroupActivity.class));
                        break;
                }
            }
        });

        iv_title_left.setOnClickListener(this);
        tv_finish_search_user.setOnClickListener(this);
        ivClear.setOnClickListener(this);
        linearTip.setOnClickListener(this);
        et_search_user.setText(search_user);
        et_search_user.setSelection(search_user.length());
        et_search_user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ll_layout_search_empty.setVisibility(View.GONE);
                ll_query_group.setVisibility(View.GONE);
                roomList.clear();
                mSearchRoomAdapter.notifyDataSetChanged();
                if (s == null || s.length() == 0) {
                    ivClear.setVisibility(View.INVISIBLE);
                    linearTip.setVisibility(View.GONE);
                    return;
                }
                ivClear.setVisibility(View.VISIBLE);
                linearTip.setVisibility(View.VISIBLE);
                String tipStr = "网络查找“<font color='#8d76fe'>" + s + "</font>”相关的群";
                tvSearchText.setText(Html.fromHtml(tipStr));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_search_user.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    onLoadData(et_search_user.getText().toString());
                    return true;
                }
                return false;
            }
        });
    }


    private void onLoadData(String keyword) {
        if (TextUtils.isEmpty(search_user)) {
            //弹出键盘输入
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            ll_query_group.setVisibility(View.GONE);
            return;
        }
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("keyword", keyword);
        HttpUtils.post().url(coreManager.getConfig().SEARCH_ROOM)
                .params(params)
                .build()
                .execute(new ListCallback(SearchUserAndRoomBean.RoomsBean.class) {

                    @Override
                    public void onResponse(ArrayResult result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            if (result.getData().size() == 0) {
                                ll_layout_search_empty.setVisibility(View.VISIBLE);
                            } else {
                                ll_layout_search_empty.setVisibility(View.GONE);
                            }
                            if (roomList.size() > 0) {
                                roomList.clear();
                            }
                            ll_query_group.setVisibility(View.VISIBLE);
                            roomList.addAll(result.getData());
                            mSearchRoomAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(NetSearchRoomsActivity.this, e.getMessage());
                    }
                });
    }
    /**
     * @author: czl
     * @description 加群
     * @date: 2019/9/18 9:28
     */
    private void roomAutoJoin(SearchUserAndRoomBean.RoomsBean room){
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId",room.getId());
        DialogHelper.showDefaulteMessageProgressDialog(NetSearchRoomsActivity.this);

        HttpUtils.post().url(coreManager.getConfig().ROOM_AUTO_JOIN)
                .params(params).build().execute(new BaseCallback<String>(String.class) {
            @Override
            public void onResponse(ObjectResult<String> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode()==1){//加入成功 直接进群
                    EventBus.getDefault().post("cancle");//关闭页面

                    //进入群聊页面
//                    Intent intent = new Intent(NetSearchRoomsActivity.this, MucChatActivity.class);
//                    intent.putExtra(AppConstant.EXTRA_USER_ID, roomJid);
//                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, roomName);
//                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
//                    startActivity(intent);
                    ToMucChatActivity(room);
                    finish();
                }else if (result.getResultCode()==1040320){//群主开启了加群验证  跳转到发送加群申请页面
                    startActivity(new Intent(NetSearchRoomsActivity.this, ApplyForAddGroupActivity.class)
                            .putExtra("RoomId",room.getId()));

                }else if (result.getResultCode()==1040319){//已加入群
                    ToastUtil.showToast(NetSearchRoomsActivity.this,result.getResultMsg());
//                    Intent intent = new Intent(NetSearchRoomsActivity.this, MucChatActivity.class);
//                    intent.putExtra(AppConstant.EXTRA_USER_ID, roomJid);
//                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, roomName);
//                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
//                    startActivity(intent);
                    ToMucChatActivity(room);
                    EventBus.getDefault().post("cancle");//关闭页面
                    finish();

                }else {
                    ToastUtil.showToast(NetSearchRoomsActivity.this,result.getResultMsg());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(NetSearchRoomsActivity.this);
            }
        });
    }

    /**
     * @author: czl
     * @description 跳转进入群聊页之前 判断本地是否存在该群
     * @date: 2019/9/27 21:21
     */
    private void ToMucChatActivity(SearchUserAndRoomBean.RoomsBean room){
        Friend mFriend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), room.getJid());
        if (mFriend==null){
            Friend mCreateFriend = new Friend();
            mCreateFriend.setOwnerId(coreManager.getSelf().getUserId());
            mCreateFriend.setUserId(room.getUserId());
            mCreateFriend.setNickName(room.getNickname());
            mCreateFriend.setDescription(room.getDesc());
            mCreateFriend.setRoomId(room.getId());
//            mCreateFriend.setContent(room.get);
            mCreateFriend.setTimeSend(room.getTalkTime());
            mCreateFriend.setRoomFlag(1);
            mCreateFriend.setStatus(Friend.STATUS_FRIEND);
            mCreateFriend.setGroupStatus(0);
            FriendDao.getInstance().createOrUpdateFriend(mCreateFriend);
            // 调用smack加入群组的方法
            // 被邀请加入群组，lastSeconds == 当前时间 - 被邀请时的时间
//            coreManager.joinMucChat(room.getJid(), 0);
        }
        Intent intent = new Intent(NetSearchRoomsActivity.this, MucChatActivity.class);
        intent.putExtra(AppConstant.EXTRA_USER_ID, room.getJid());
        intent.putExtra(AppConstant.EXTRA_NICK_NAME, room.getName());
        intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if (v == iv_title_left) {
            finish();
        } else if (v == tv_finish_search_user) {
            EventBus.getDefault().post("cancle");
            finish();
        } else if (v == linearTip) {
            linearTip.setVisibility(View.GONE);
            search_user = et_search_user.getText().toString();
            onLoadData(search_user);
        } else if (v == ivClear) {
            et_search_user.setText("");
        }
    }
}
